
var Api = require('../../utils/api.js');
var util = require('../../utils/util.js');

var wxApi = require('../../utils/wxApi.js')
var wxRequest = require('../../utils/wxRequest.js')
import config from '../../utils/config.js'
const Adapter = require('../../utils/adapter.js')
var pageCount = config.getPageCount;

var webSiteName = config.getWebsiteName;
var domain = config.getDomain;

Page({
  data: {
    logoImageurl:'', 
    videoPath:'',
    isLastPage: false, 
    page: 1,
    search: '',
    showerror: "none",
    floatDisplay: "none",
    listAdsuccess: true,
    webSiteName: webSiteName,
    domain: domain,
    isFirst: false, // 是否第一次打开,
    isLoading: false,
    swipe_nav: [],
    selected_nav: [],
    company_profile:"",
    advantage:"",
    windowHeight:'100%',
    windowWidth:'100%',
    boutique:[]
  },
  formSubmit: function (e) {
    var url = '../list/list'
    var key = '';
    if (e.currentTarget.id == "search-input") {
      key = e.detail.value;
    } else {

      key = e.detail.value.input;

    }
    if (key != '') {
      url = url + '?search=' + key;
      wx.navigateTo({
        url: url
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请输入内容',
        showCancel: false,
      });
    }
  },
  onShareAppMessage: function () {
    return {
      title: '“' + webSiteName + '”小程序,基于微慕WordPress版小程序构建',
      path: 'pages/index/index',
      appInfo:{
        'appId':config.appghId
      },
      success: function (res) {
        // 转发成功
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },
  // 自定义分享朋友圈
  onShareTimeline: function () {
    return {
      title: '“' + webSiteName + '”小程序,基于微慕WordPress版小程序构建',
      path: 'pages/index/index',
    }
  },
  onReachBottom: function () {

    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      console.log('当前页' + self.data.page);
    
    } else {
      console.log('最后一页');
    }

  },
  onLoad: function (options) {
 
    var self = this;
    wx.showShareMenu({
      withShareTicket: true,
      menus: ['shareAppMessage', 'shareTimeline'],
      success: function (e) {
        //console.log(e);
      }
    })
    // 设置页面标题：文章分类
    wx.setNavigationBarTitle({
      title: webSiteName 
    });
    Adapter.setInterstitialAd("enable_index_interstitial_ad");

    // 判断用户是不是第一次打开，弹出添加到我的小程序提示
    var isFirstStorage = wx.getStorageSync('isFirst');
    // console.log(isFirstStorage);
    if (!isFirstStorage) {
      self.setData({
        isFirst: true
      });
      wx.setStorageSync('isFirst', 'no')
      // console.log(wx.getStorageSync('isFirst'));
      setTimeout(function () {
        self.setData({
          isFirst: false
        });
      }, 5000)
    }
    wx.getSystemInfo({
      success: (result) => {
        // console.log(result.windowWidth);
        self.setData({
          windowHeight:result.windowHeight,
          windowWidth:result.windowWidth
        })
      },
    })
    this.getHomeconfig();

  },
  onShow: function (options) {
    if (typeof this.getTabBar === 'function' &&
    this.getTabBar()) {
    this.getTabBar().setData({
      selected: 0
    })
  }
    wx.setStorageSync('openLinkCount', 0);

    var nowDate = new Date();
    nowDate = nowDate.getFullYear() + "-" + (nowDate.getMonth() + 1) + '-' + nowDate.getDate();
    nowDate = new Date(nowDate).getTime();
    var _openAdLogs = wx.getStorageSync('openAdLogs') || [];
    var openAdLogs = [];
    _openAdLogs.map(function (log) {
      if (new Date(log["date"]).getTime() >= nowDate) {
        openAdLogs.unshift(log);
      }

    })

    wx.setStorageSync('openAdLogs', openAdLogs);
    console.log(wx.getStorageSync('openAdLogs'));

  },
  formatImg (html) {
    var newContent = html.replace(/<img[^>]*>/gi, (match) => {
      let processed=null;
      if(!match.match(/style=\"(.*)\"/gi)){
        processed=match.replace(/\<img/g, '<img style="width:100%;height:auto;display:block"');
      }else{
        processed = match.replace(/style=\"(.*)\"/gi, 'style="width:100%;height:auto;display:block"');
      }
      return processed;
    });
    return newContent;
  },

  getHomeconfig() {
    //获取扩展设置
    var self = this;
    var getHomeconfig = wxRequest.getRequest(Api.get_homeconfig());
    getHomeconfig.then(res => {
      console.log(res.data); 
      let expand = res.data.expand; 
      let swipe_nav = expand.swipe_nav;
      let boutique = expand.boutique;
      let selected_nav = expand.selected_nav;
      let _d = res.data.downloadfileDomain
      let _b = res.data.businessDomain 
      let videoPath = expand.mainVideo;
      let zanImageurl = res.data.zanImageurl  
      let logoImageurl = res.data.logoImageurl
      let company_profile = res.data.company_profile
      let advantage = res.data.advantage
      let downloadfileDomain = _d.length ? _d.split(',') : []
      let businessDomain = _b.length ? _b.split(',') : []
      self.setData({
        videoPath:videoPath, 
        swipe_nav: swipe_nav,
        logoImageurl:logoImageurl,
        selected_nav:selected_nav,
        company_profile:self.formatImg(company_profile) ,
        advantage:self.formatImg(advantage),
        boutique:boutique
      }); 
      wx.setStorageSync('downloadfileDomain', downloadfileDomain);
      wx.setStorageSync('businessDomain', businessDomain);
      wx.setStorageSync('zanImageurl', zanImageurl);
      wx.setStorageSync('logoImageurl', logoImageurl);
    });
  },
  //加载分页
  loadMore: function (e) {
    var self = this;
    if (!self.data.isLastPage) {
      self.setData({
        page: self.data.page + 1
      });
      console.log('当前页' + self.data.page);
    } else {
      wx.showToast({
        title: '没有更多内容',
        mask: false,
        duration: 1000
      });
    }
  },
  // 跳转至查看文章详情
  redictDetail: function (e) {
    // console.log('查看文章');
    var id = e.currentTarget.id,
      url = '../detail/detail?id=' + id;
    wx.navigateTo({
      url: url
    })
  },
 
  // 跳转至查看小程序列表页面或文章详情页
  redictAppDetail: function (e) {
    let {
      type,
      appid,
      url,
      path,
      jumptype
    } = e.currentTarget.dataset
    if (type === 'apppage') { // 小程序页面         
      wx.navigateTo({
        url: path
      })
    }
    if (type === 'webpage') { // web-view页面
      url = '../webpage/webpage?url=' + encodeURIComponent(url)
      wx.navigateTo({
        url: url
      })
    }
    if (type === 'miniapp') { // 其他小程序
      if(jumptype=='embedded')
      {
        wx.openEmbeddedMiniProgram({
          appId: appid,
          path: path
        })
      }
      else
      {
        wx.navigateToMiniProgram({
          appId: appid,
          path: path
        })
      }
    }
  },
  //返回首页 
  redictHome: function (e) {
    //console.log('查看某类别下的文章');  
    var id = e.currentTarget.dataset.id,
      url = '/pages/index/index';
    wx.switchTab({
      url: url
    });
  },
  adbinderror: function (e) {
    var self = this;
    console.log(e.detail.errCode);
    console.log(e.detail.errMsg);
    if (e.detail.errCode) {
      self.setData({
        listAdsuccess: false
      })
    }

  },
  videoErrorCallback(e) {
    console.log('视频错误信息:')
    console.log(e.detail.errMsg)
  }
})